# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/11 18:57 
@Author  : ZhangShenao 
@File    : canceled_worker.py
@Desc    : 异步任务可以取消
"""
import asyncio

from bacis.decorator.perf_log_decorator import perf_log


async def worker1() -> int:
    print('worker1 start')
    await asyncio.sleep(1)
    print('worker1 end')
    return 1


async def worker2() -> int:
    print('worker2 start')
    await asyncio.sleep(2)
    print('worker2 end')
    return 2 / 0  # 模拟执行异常


async def worker3() -> int:
    print('worker3 start')
    await asyncio.sleep(3)
    print('worker3 end')
    return 3


async def main():
    # 创建异步任务
    task1 = asyncio.create_task(worker1())
    task2 = asyncio.create_task(worker2())
    task3 = asyncio.create_task(worker3())

    await asyncio.sleep(2)

    # 调用cancel()函数,取消任务,最终结果会返回CancelledError
    task3.cancel()

    # 执行异步任务
    res = await asyncio.gather(task1, task2, task3, return_exceptions=True)  # 指定返回异常信息,避免将异常抛到执行层

    # [1, ZeroDivisionError('division by zero'), CancelledError('')]
    print(res)


@perf_log
def run():
    asyncio.run(main())


run()
